import { _decorator, Component, Node, Label, Sprite, EventHandler, SpriteFrame } from 'cc';
import AssetsMgr from '../../Model/AssetsMgr';
import { Global, TechnologyType, TechnologyData } from '../../Util/Global';
import { Tools } from '../../Util/Tools';
import GameEventMgr, { GameEvent } from '../../Model/GameEventMgr';
import SoundCtrl from '../../Ctrl/SoundCtrl';
const { ccclass, property } = _decorator;

@ccclass('TechnologyItem')
export class TechnologyItem extends Component {

    @property({ type: Sprite })
    public icon: Sprite = null;
    @property({ type: Label })
    public txtTopRight: Label = null;
    @property({ type: Label })
    public txtTopLeft: Label = null;
    @property({ type: Label })
    public txtButtom: Label = null;
    @property({ type: Sprite })
    public lockMask: Sprite = null;

    set technologyType(value) {
        this._technologyType = value;
        this.updateData();
    }
    get technologyType() {
        return this._technologyType;
    }
    _technologyType: TechnologyType = TechnologyType.PlanetWarning;

    technologyData: TechnologyData = null;

    activate: boolean = false;
    updateData() {
        let lv = Global.gameManager.playerData.technologyProduct.get(this._technologyType) || 0;
        this.activate = lv > 0;
        this.lockMask.node.active = !this.activate;
        this.icon.color = this.activate ? Tools.hex2color('#2AD8D8') : Tools.hex2color('#7E7E7E');

        this.technologyData = TechnologyData.TechnologyMap.get(this._technologyType);
        this.txtButtom.string = this.activate ? '' : this.technologyData.name;

        this.txtTopRight.string = lv < this.technologyData.levelMax ?
            this.technologyData.cost * (lv + 1) + '' : 'max';
        this.txtTopLeft.string = this.activate ? 'lv' + lv : '';
        AssetsMgr.getRes(this.technologyData.iconPath, SpriteFrame, (icon) => {
            if (this.icon && this.icon.isValid) {
                this.icon.spriteFrame = icon;
            }
        })
    }

    public OnClick(event: EventHandler, customEventData: string) {
        let playerData = Global.gameManager.playerData;

        let lv = playerData.technologyProduct.get(this._technologyType) || 0;
        if (playerData && lv < this.technologyData.levelMax
            && playerData.technologyPoint >= this.technologyData.cost * (lv + 1)) {

            lv = Global.gameManager.playerUnit.levelUpCom.UpTechnology(this._technologyType);
            if (lv > 0) {
                playerData.technologyPoint -= this.technologyData.cost * lv;
                GameEventMgr.Dispatch(GameEvent.PlayerDataChange);
                GameEventMgr.Dispatch(GameEvent.ActivateTechnology, this._technologyType, lv);
            }
            SoundCtrl.playEffect('forceField_000', 0.2);
        }
        else {
            SoundCtrl.playEffect('mouserelease1');
        }
    }
}


